package com.mapper;

import com.dto.CommentsWithUserDTO;
import com.pojo.Comments;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CommentsMapper {

    @Select("SELECT user_id FROM comments WHERE id = #{commentId}")
    Integer selectUserIdByCommentId(Integer commentId);


    // 根据笔记ID查询评论（包含用户信息）
    @Select("SELECT c.*, u.nickname, u.avatar_url as avatarUrl " +
            "FROM comments c " +
            "JOIN users u ON c.user_id = u.id " + // 修改为 users
            "WHERE c.note_id = #{noteId}")
    List<CommentsWithUserDTO> selectCommentsWithUserByNoteId(Integer noteId);

    // 根据父评论ID查询回复（包含用户信息）
    @Select("SELECT c.*, u.nickname, u.avatar_url as avatarUrl " +
            "FROM comments c " +
            "JOIN users u ON c.user_id = u.id " + // 修改为 users
            "WHERE c.parent_id = #{parentId}")
    List<CommentsWithUserDTO> selectRepliesWithUserByParentId(Integer parentId);

    // 插入评论
    @Insert("INSERT INTO comments(user_id, note_id, content, parent_id, created_at, updated_at) " +
            "VALUES(#{userId}, #{noteId}, #{content}, #{parentId}, #{createdAt}, #{updatedAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Comments comment);

    // 更新评论
    @Update("UPDATE comments SET " +
            "content = #{content}, " +
            "updated_at = #{updatedAt} " +
            "WHERE id = #{id}")
    int update(Comments comment);

    // 删除评论
    @Delete("DELETE FROM comments WHERE id = #{id}")
    int delete(Integer id);

    // 删除笔记的所有评论
    @Delete("DELETE FROM comments WHERE note_id = #{noteId}")
    int deleteByNoteId(Integer noteId);

    // 删除指定父评论的所有回复
    @Delete("DELETE FROM comments WHERE parent_id = #{parentId}")
    int deleteByParentId(Integer parentId);

    // 删除笔记的所有回复（非顶级评论）
    @Delete("DELETE FROM comments WHERE note_id = #{noteId} AND parent_id != 0")
    int deleteRepliesByNoteId(Integer noteId);

    // 根据ID查询评论
    @Select("SELECT * FROM comments WHERE id = #{id}")
    Comments selectById(Integer id);

    // 根据笔记ID查询评论
    @Select("SELECT * FROM comments WHERE note_id = #{noteId} ORDER BY created_at ASC")
    List<Comments> selectByNoteId(Integer noteId);

    // 根据用户ID查询评论
    @Select("SELECT * FROM comments WHERE user_id = #{userId} ORDER BY created_at DESC")
    List<Comments> selectByUserId(Integer userId);

    // 根据父评论ID查询回复
    @Select("SELECT * FROM comments WHERE parent_id = #{parentId} ORDER BY created_at ASC")
    List<Comments> selectByParentId(Integer parentId);

    // 统计笔记的评论数
    @Select("SELECT COUNT(*) FROM comments WHERE note_id = #{noteId}")
    int countByNoteId(Integer noteId);

    // 统计用户的评论数
    @Select("SELECT COUNT(*) FROM comments WHERE user_id = #{userId}")
    int countByUserId(Integer userId);
}